"""
分析决策流程

定义投资分析和决策制定的工作流程。
"""

from typing import Dict, List, Any, Optional
from datetime import datetime, timedelta

from .workflow_types import (
    WorkflowDefinition,
    WorkflowNode,
    WorkflowEdge,
    WorkflowType,
    NodeType,
    EdgeType
)


class AnalysisDecisionFlow:
    """
    分析决策流程构建器
    
    负责构建投资分析和决策相关的工作流定义。
    """
    
    @staticmethod
    def create_investment_analysis_flow() -> WorkflowDefinition:
        """
        创建投资分析流程
        
        Returns:
            投资分析工作流定义
        """
        workflow = WorkflowDefinition(
            workflow_id="investment_analysis",
            name="投资分析流程",
            workflow_type=WorkflowType.ANALYSIS_DECISION,
            description="全面的投资分析和决策制定流程",
            timeout=timedelta(hours=2)
        )
        
        # 开始节点
        start_node = WorkflowNode(
            node_id="start",
            name="开始",
            node_type=NodeType.START,
            description="投资分析流程开始"
        )
        workflow.add_node(start_node)
        workflow.start_node_id = "start"
        
        # 数据准备节点
        data_preparation = WorkflowNode(
            node_id="data_preparation",
            name="数据准备",
            node_type=NodeType.TASK,
            description="准备分析所需的数据",
            executor="data_preparator",
            timeout=timedelta(minutes=15),
            parameters={
                "data_sources": ["market_data", "fundamental_data", "alternative_data"],
                "time_range": "from_context",
                "symbols": "from_context",
                "data_quality_check": True
            }
        )
        workflow.add_node(data_preparation)
        
        # 分析类型决策
        analysis_type_decision = WorkflowNode(
            node_id="analysis_type_decision",
            name="分析类型决策",
            node_type=NodeType.DECISION,
            description="根据投资目标决定分析类型",
            conditions=[
                {
                    "name": "fundamental_analysis",
                    "expression": "analysis_request['type'] in ['fundamental', 'value_investing']"
                },
                {
                    "name": "technical_analysis",
                    "expression": "analysis_request['type'] in ['technical', 'momentum']"
                },
                {
                    "name": "quantitative_analysis",
                    "expression": "analysis_request['type'] in ['quantitative', 'factor_model']"
                },
                {
                    "name": "comprehensive_analysis",
                    "expression": "analysis_request['type'] == 'comprehensive'"
                }
            ]
        )
        workflow.add_node(analysis_type_decision)
        
        # 并行分析执行
        parallel_analysis = WorkflowNode(
            node_id="parallel_analysis",
            name="并行分析执行",
            node_type=NodeType.PARALLEL,
            description="并行执行多种分析",
            parallel_branches=["fundamental_analysis", "technical_analysis", "quantitative_analysis", "risk_analysis"]
        )
        workflow.add_node(parallel_analysis)
        
        # 基本面分析
        fundamental_analysis = WorkflowNode(
            node_id="fundamental_analysis",
            name="基本面分析",
            node_type=NodeType.TASK,
            description="执行基本面分析",
            executor="fundamental_analyzer",
            timeout=timedelta(minutes=30),
            parameters={
                "analysis_methods": [
                    "financial_ratio_analysis",
                    "dcf_valuation",
                    "comparable_company_analysis",
                    "industry_analysis",
                    "management_quality_assessment"
                ],
                "valuation_models": ["dcf", "ddm", "pe_multiple", "ev_ebitda"],
                "peer_comparison": True
            }
        )
        workflow.add_node(fundamental_analysis)
        
        # 技术分析
        technical_analysis = WorkflowNode(
            node_id="technical_analysis",
            name="技术分析",
            node_type=NodeType.TASK,
            description="执行技术分析",
            executor="technical_analyzer",
            timeout=timedelta(minutes=20),
            parameters={
                "indicators": [
                    "moving_averages",
                    "rsi",
                    "macd",
                    "bollinger_bands",
                    "fibonacci_retracements",
                    "support_resistance"
                ],
                "chart_patterns": [
                    "head_shoulders",
                    "triangles",
                    "flags_pennants",
                    "double_top_bottom"
                ],
                "timeframes": ["1d", "1w", "1m"]
            }
        )
        workflow.add_node(technical_analysis)
        
        # 量化分析
        quantitative_analysis = WorkflowNode(
            node_id="quantitative_analysis",
            name="量化分析",
            node_type=NodeType.TASK,
            description="执行量化分析",
            executor="quantitative_analyzer",
            timeout=timedelta(minutes=45),
            parameters={
                "factor_models": [
                    "fama_french_3factor",
                    "fama_french_5factor",
                    "carhart_4factor",
                    "custom_factors"
                ],
                "statistical_tests": [
                    "stationarity_test",
                    "cointegration_test",
                    "correlation_analysis",
                    "regression_analysis"
                ],
                "machine_learning": {
                    "models": ["random_forest", "xgboost", "lstm"],
                    "features": "auto_generate",
                    "cross_validation": True
                }
            }
        )
        workflow.add_node(quantitative_analysis)
        
        # 风险分析
        risk_analysis = WorkflowNode(
            node_id="risk_analysis",
            name="风险分析",
            node_type=NodeType.TASK,
            description="执行风险分析",
            executor="risk_analyzer",
            timeout=timedelta(minutes=25),
            parameters={
                "risk_metrics": [
                    "var",
                    "cvar",
                    "maximum_drawdown",
                    "sharpe_ratio",
                    "sortino_ratio",
                    "beta",
                    "tracking_error"
                ],
                "stress_testing": {
                    "scenarios": ["market_crash", "interest_rate_shock", "sector_rotation"],
                    "monte_carlo_simulations": 10000
                },
                "correlation_analysis": True
            }
        )
        workflow.add_node(risk_analysis)
        
        # 分析结果整合
        analysis_integration = WorkflowNode(
            node_id="analysis_integration",
            name="分析结果整合",
            node_type=NodeType.TASK,
            description="整合各种分析结果",
            executor="analysis_integrator",
            parameters={
                "integration_methods": [
                    "weighted_scoring",
                    "consensus_building",
                    "conflict_resolution"
                ],
                "weights": {
                    "fundamental": 0.4,
                    "technical": 0.3,
                    "quantitative": 0.2,
                    "risk": 0.1
                }
            }
        )
        workflow.add_node(analysis_integration)
        
        # 投资建议生成
        recommendation_generation = WorkflowNode(
            node_id="recommendation_generation",
            name="投资建议生成",
            node_type=NodeType.TASK,
            description="生成投资建议",
            executor="recommendation_generator",
            parameters={
                "recommendation_types": ["buy", "sell", "hold", "strong_buy", "strong_sell"],
                "confidence_scoring": True,
                "target_price_calculation": True,
                "time_horizon": "from_context"
            }
        )
        workflow.add_node(recommendation_generation)
        
        # 决策验证
        decision_validation = WorkflowNode(
            node_id="decision_validation",
            name="决策验证",
            node_type=NodeType.TASK,
            description="验证投资决策的合理性",
            executor="decision_validator",
            parameters={
                "validation_checks": [
                    "consistency_check",
                    "risk_budget_check",
                    "correlation_check",
                    "liquidity_check",
                    "regulatory_compliance"
                ],
                "approval_thresholds": {
                    "confidence_min": 0.7,
                    "risk_max": 0.15
                }
            }
        )
        workflow.add_node(decision_validation)
        
        # 决策审批流程
        approval_process = WorkflowNode(
            node_id="approval_process",
            name="决策审批流程",
            node_type=NodeType.DECISION,
            description="根据决策规模和风险确定审批流程",
            conditions=[
                {
                    "name": "auto_approve",
                    "expression": "decision_amount < auto_approval_limit and risk_score < low_risk_threshold"
                },
                {
                    "name": "manager_approval",
                    "expression": "decision_amount < manager_approval_limit and risk_score < medium_risk_threshold"
                },
                {
                    "name": "committee_approval",
                    "expression": "decision_amount >= manager_approval_limit or risk_score >= medium_risk_threshold"
                }
            ]
        )
        workflow.add_node(approval_process)
        
        # 自动审批
        auto_approval = WorkflowNode(
            node_id="auto_approval",
            name="自动审批",
            node_type=NodeType.TASK,
            description="自动审批低风险决策",
            executor="auto_approver",
            parameters={
                "approval_criteria": "predefined_rules",
                "logging": True
            }
        )
        workflow.add_node(auto_approval)
        
        # 经理审批
        manager_approval = WorkflowNode(
            node_id="manager_approval",
            name="经理审批",
            node_type=NodeType.TASK,
            description="投资经理审批",
            executor="manager_approver",
            parameters={
                "notification_channels": ["email", "system_message"],
                "timeout": timedelta(hours=4),
                "escalation_rules": True
            }
        )
        workflow.add_node(manager_approval)
        
        # 委员会审批
        committee_approval = WorkflowNode(
            node_id="committee_approval",
            name="委员会审批",
            node_type=NodeType.TASK,
            description="投资委员会审批",
            executor="committee_approver",
            parameters={
                "committee_members": "from_config",
                "voting_mechanism": "majority",
                "meeting_scheduling": True
            }
        )
        workflow.add_node(committee_approval)
        
        # 决策记录
        decision_recording = WorkflowNode(
            node_id="decision_recording",
            name="决策记录",
            node_type=NodeType.TASK,
            description="记录投资决策",
            executor="decision_recorder",
            parameters={
                "storage_systems": ["database", "audit_log", "compliance_system"],
                "record_format": "structured",
                "retention_period": "7_years"
            }
        )
        workflow.add_node(decision_recording)
        
        # 结束节点
        end_node = WorkflowNode(
            node_id="end",
            name="结束",
            node_type=NodeType.END,
            description="投资分析流程结束"
        )
        workflow.add_node(end_node)
        workflow.end_node_ids = ["end"]
        
        # 添加边
        edges = [
            # 主流程
            WorkflowEdge("edge_1", "start", "data_preparation", EdgeType.SEQUENCE),
            WorkflowEdge("edge_2", "data_preparation", "analysis_type_decision", EdgeType.SEQUENCE),
            
            # 分析类型分支
            WorkflowEdge("edge_3", "analysis_type_decision", "parallel_analysis", EdgeType.CONDITION,
                        condition="any([analysis_type_decision_result[key] for key in analysis_type_decision_result])"),
            
            # 分析整合
            WorkflowEdge("edge_4", "parallel_analysis", "analysis_integration", EdgeType.SEQUENCE),
            WorkflowEdge("edge_5", "analysis_integration", "recommendation_generation", EdgeType.SEQUENCE),
            WorkflowEdge("edge_6", "recommendation_generation", "decision_validation", EdgeType.SEQUENCE),
            WorkflowEdge("edge_7", "decision_validation", "approval_process", EdgeType.SEQUENCE),
            
            # 审批分支
            WorkflowEdge("edge_8", "approval_process", "auto_approval", EdgeType.CONDITION,
                        condition="approval_process_result['auto_approve']"),
            WorkflowEdge("edge_9", "approval_process", "manager_approval", EdgeType.CONDITION,
                        condition="approval_process_result['manager_approval']"),
            WorkflowEdge("edge_10", "approval_process", "committee_approval", EdgeType.CONDITION,
                        condition="approval_process_result['committee_approval']"),
            
            # 审批后流程
            WorkflowEdge("edge_11", "auto_approval", "decision_recording", EdgeType.SEQUENCE),
            WorkflowEdge("edge_12", "manager_approval", "decision_recording", EdgeType.SEQUENCE),
            WorkflowEdge("edge_13", "committee_approval", "decision_recording", EdgeType.SEQUENCE),
            WorkflowEdge("edge_14", "decision_recording", "end", EdgeType.SEQUENCE),
        ]
        
        for edge in edges:
            workflow.add_edge(edge)
        
        # 设置输入输出模式
        workflow.input_schema = {
            "type": "object",
            "properties": {
                "symbols": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "要分析的股票代码列表"
                },
                "analysis_type": {
                    "type": "string",
                    "enum": ["fundamental", "technical", "quantitative", "comprehensive"],
                    "description": "分析类型"
                },
                "investment_amount": {
                    "type": "number",
                    "description": "投资金额"
                },
                "time_horizon": {
                    "type": "string",
                    "enum": ["short_term", "medium_term", "long_term"],
                    "description": "投资时间范围"
                },
                "risk_tolerance": {
                    "type": "string",
                    "enum": ["conservative", "moderate", "aggressive"],
                    "description": "风险承受能力"
                }
            },
            "required": ["symbols", "analysis_type"]
        }
        
        workflow.output_schema = {
            "type": "object",
            "properties": {
                "recommendations": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "symbol": {"type": "string"},
                            "recommendation": {"type": "string"},
                            "confidence": {"type": "number"},
                            "target_price": {"type": "number"},
                            "reasoning": {"type": "string"}
                        }
                    }
                },
                "analysis_summary": {"type": "object"},
                "risk_assessment": {"type": "object"},
                "approval_status": {"type": "string"}
            }
        }
        
        return workflow
    
    @staticmethod
    def create_portfolio_optimization_flow() -> WorkflowDefinition:
        """
        创建投资组合优化流程
        
        Returns:
            投资组合优化工作流定义
        """
        workflow = WorkflowDefinition(
            workflow_id="portfolio_optimization",
            name="投资组合优化流程",
            workflow_type=WorkflowType.ANALYSIS_DECISION,
            description="投资组合构建和优化流程",
            timeout=timedelta(hours=1)
        )
        
        # 开始节点
        start_node = WorkflowNode(
            node_id="start",
            name="开始",
            node_type=NodeType.START
        )
        workflow.add_node(start_node)
        workflow.start_node_id = "start"
        
        # 投资组合分析
        portfolio_analysis = WorkflowNode(
            node_id="portfolio_analysis",
            name="投资组合分析",
            node_type=NodeType.TASK,
            description="分析当前投资组合",
            executor="portfolio_analyzer",
            parameters={
                "analysis_metrics": [
                    "return_analysis",
                    "risk_analysis",
                    "correlation_analysis",
                    "sector_allocation",
                    "style_analysis"
                ]
            }
        )
        workflow.add_node(portfolio_analysis)
        
        # 优化目标设定
        optimization_objectives = WorkflowNode(
            node_id="optimization_objectives",
            name="优化目标设定",
            node_type=NodeType.TASK,
            description="设定优化目标和约束",
            executor="objective_setter",
            parameters={
                "objectives": ["maximize_return", "minimize_risk", "maximize_sharpe"],
                "constraints": [
                    "position_limits",
                    "sector_limits",
                    "turnover_limits",
                    "liquidity_constraints"
                ]
            }
        )
        workflow.add_node(optimization_objectives)
        
        # 优化算法执行
        optimization_execution = WorkflowNode(
            node_id="optimization_execution",
            name="优化算法执行",
            node_type=NodeType.TASK,
            description="执行投资组合优化算法",
            executor="portfolio_optimizer",
            parameters={
                "algorithms": [
                    "mean_variance_optimization",
                    "black_litterman",
                    "risk_parity",
                    "genetic_algorithm"
                ],
                "rebalancing_frequency": "monthly"
            }
        )
        workflow.add_node(optimization_execution)
        
        # 结果验证
        result_validation = WorkflowNode(
            node_id="result_validation",
            name="结果验证",
            node_type=NodeType.TASK,
            description="验证优化结果",
            executor="result_validator",
            parameters={
                "validation_tests": [
                    "backtesting",
                    "stress_testing",
                    "scenario_analysis"
                ]
            }
        )
        workflow.add_node(result_validation)
        
        # 结束节点
        end_node = WorkflowNode(
            node_id="end",
            name="结束",
            node_type=NodeType.END
        )
        workflow.add_node(end_node)
        workflow.end_node_ids = ["end"]
        
        # 添加边
        edges = [
            WorkflowEdge("edge_1", "start", "portfolio_analysis", EdgeType.SEQUENCE),
            WorkflowEdge("edge_2", "portfolio_analysis", "optimization_objectives", EdgeType.SEQUENCE),
            WorkflowEdge("edge_3", "optimization_objectives", "optimization_execution", EdgeType.SEQUENCE),
            WorkflowEdge("edge_4", "optimization_execution", "result_validation", EdgeType.SEQUENCE),
            WorkflowEdge("edge_5", "result_validation", "end", EdgeType.SEQUENCE),
        ]
        
        for edge in edges:
            workflow.add_edge(edge)
        
        return workflow
    
    @staticmethod
    def create_risk_assessment_flow() -> WorkflowDefinition:
        """
        创建风险评估流程
        
        Returns:
            风险评估工作流定义
        """
        workflow = WorkflowDefinition(
            workflow_id="risk_assessment",
            name="风险评估流程",
            workflow_type=WorkflowType.ANALYSIS_DECISION,
            description="全面的投资风险评估流程",
            timeout=timedelta(minutes=45)
        )
        
        # 开始节点
        start_node = WorkflowNode(
            node_id="start",
            name="开始",
            node_type=NodeType.START
        )
        workflow.add_node(start_node)
        workflow.start_node_id = "start"
        
        # 风险识别
        risk_identification = WorkflowNode(
            node_id="risk_identification",
            name="风险识别",
            node_type=NodeType.TASK,
            description="识别各类投资风险",
            executor="risk_identifier",
            parameters={
                "risk_categories": [
                    "market_risk",
                    "credit_risk",
                    "liquidity_risk",
                    "operational_risk",
                    "regulatory_risk",
                    "concentration_risk"
                ]
            }
        )
        workflow.add_node(risk_identification)
        
        # 风险量化
        risk_quantification = WorkflowNode(
            node_id="risk_quantification",
            name="风险量化",
            node_type=NodeType.TASK,
            description="量化识别的风险",
            executor="risk_quantifier",
            parameters={
                "quantification_methods": [
                    "var_calculation",
                    "stress_testing",
                    "scenario_analysis",
                    "monte_carlo_simulation"
                ]
            }
        )
        workflow.add_node(risk_quantification)
        
        # 风险评级
        risk_rating = WorkflowNode(
            node_id="risk_rating",
            name="风险评级",
            node_type=NodeType.TASK,
            description="对风险进行评级",
            executor="risk_rater",
            parameters={
                "rating_scale": ["low", "medium", "high", "critical"],
                "rating_criteria": "predefined_matrix"
            }
        )
        workflow.add_node(risk_rating)
        
        # 结束节点
        end_node = WorkflowNode(
            node_id="end",
            name="结束",
            node_type=NodeType.END
        )
        workflow.add_node(end_node)
        workflow.end_node_ids = ["end"]
        
        # 添加边
        edges = [
            WorkflowEdge("edge_1", "start", "risk_identification", EdgeType.SEQUENCE),
            WorkflowEdge("edge_2", "risk_identification", "risk_quantification", EdgeType.SEQUENCE),
            WorkflowEdge("edge_3", "risk_quantification", "risk_rating", EdgeType.SEQUENCE),
            WorkflowEdge("edge_4", "risk_rating", "end", EdgeType.SEQUENCE),
        ]
        
        for edge in edges:
            workflow.add_edge(edge)
        
        return workflow